package cn.com.newloading.ribbon.util;

import cn.com.newloading.common.utils.mq.MQConnectionUtil;
import cn.com.newloading.common.utils.mq.MQMsgUtil;
import cn.com.newloading.ribbon.service.TestService;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author qja
 * @date 2021-2021/5/25-11:39
 * @describe
 */
public class MQSendUtil {
    private static Logger logger = LoggerFactory.getLogger(MQSendUtil.class);
    /**
     * 发送MQ消息
     * @param msg
     */
    public static void simpleQueueSend(String msg) throws IOException, TimeoutException {
        Connection connection = MQConnectionUtil.getConnection();//获取连接
        Channel channel = connection.createChannel();//创建通道
        /**
         *  声明队列
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         * queue:队列名字
         * durable：是否持久化, 队列的声明默认是存放到内存中的，如果rabbitmq重启会丢失
         * exclusive：是否排外的，有两个作用，一：当连接关闭时connection.close()该队列是否会自动删除；二：该队列是否是私有的private，如果不是排外的，可以使用两个消费者都访问同一个队列，没有任何问题，如果是排外的，会对当前队列加锁，其他通道channel是不能访问的，如果强制访问会报异常：com.rabbitmq.client.ShutdownSignalException:
         * autoDelete：是否自动删除队列，当最后一个消费者断开连接之后队列是否自动被删除，
         * args：相关参数，目前一般为null
         */
        channel.queueDeclare(MQMsgUtil.SIMPLE_QUEUE,false,false,false,null);
        //发送消息
        //exchange 交换机
        //routingKey 路由键
        //props 基本属性设置
        //body 消息体，真正需要发送的消息
        channel.basicPublish("",MQMsgUtil.SIMPLE_QUEUE,null,msg.getBytes());
        logger.info("============send message success:" + msg);
        channel.close();
        connection.close();
    }

    /**
     * 工作队列-轮询分发
     * @param msg
     * @throws IOException
     * @throws TimeoutException
     * @throws InterruptedException
     */
    public static void workQueueSend1(String msg) throws IOException, TimeoutException, InterruptedException {
        Connection connection = MQConnectionUtil.getConnection();//获取连接
        Channel channel = connection.createChannel();//创建通道
        channel.queueDeclare(MQMsgUtil.WORK_QUEUE_1,false,false,false,null);
        int count = 50;
        for(int i = 0;i < count;i++){
            channel.basicPublish("",MQMsgUtil.WORK_QUEUE_1,null,(msg+"["+i+"]").getBytes());
            logger.info("============send message success:" + (msg+"["+i+"]"));
            Thread.sleep(100);
        }
        channel.close();
        connection.close();
    }
}
